<template>
    <div class="company-page">

        <el-descriptions class="margin-top" title="公司简介" :column="3" :size="size" border v-loading="loading">
            <template #extra>
                <el-button type="primary" @click="openEditMainCompany">编辑</el-button>
            </template>
            <el-descriptions-item>
                <template #label>
                    <div class="cell-item">
                        <el-icon :style="iconStyle">
                            <OfficeBuilding />
                        </el-icon>
                        公司名称
                    </div>
                </template>
                {{ currentCompany.name || '—' }}
            </el-descriptions-item>
            <el-descriptions-item>
                <template #label>
                    <div class="cell-item">
                        <el-icon :style="iconStyle">
                            <Iphone />
                        </el-icon>
                        联系人电话
                    </div>
                </template>
                {{ currentCompany.phone || '—' }}
            </el-descriptions-item>
            <el-descriptions-item>
                <template #label>
                    <div class="cell-item">
                        <el-icon :style="iconStyle">
                            <OfficeBuilding />
                        </el-icon>
                        公司编号
                    </div>
                </template>
                {{ currentCompany.code || '—' }}
            </el-descriptions-item>
            <el-descriptions-item>
                <template #label>
                    <div class="cell-item">
                        <el-icon :style="iconStyle">
                            <Location />
                        </el-icon>
                        详细地址
                    </div>
                </template>
                {{ currentCompany.address || '—' }}
            </el-descriptions-item>
        </el-descriptions>

        <el-table :data="treeData" row-key="id" default-expand-all
            :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" border
            style="width: 100%; margin-top: 16px" v-loading="loading">
            <el-table-column prop="name" label="公司名称" width="300" />
            <el-table-column prop="code" label="公司编码" width="150" />
            <el-table-column prop="level" label="公司级别">
                <template #default="scope">
                    {{ getLevelText(scope.row.level) }}
                </template>
            </el-table-column>
            <el-table-column label="操作" width="180">
                <template #default="scope">
                    <el-button size="small" @click="openAddDialog(scope.row)" :disabled="scope.row.level >= 3">
                        添加子公司
                    </el-button>
                    <el-button v-if="scope.row.level > 0" size="small" type="danger" @click="handleDelete(scope.row)">
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>


        <el-dialog v-model="editMainDialogVisible" title="编辑公司信息" width="400">
            <el-form :model="mainCompanyForm" label-width="100px" :rules="mainCompanyRules" ref="mainCompanyFormRef">
                <el-form-item label="公司名称" prop="name">
                    <el-input v-model="mainCompanyForm.name" placeholder="请输入公司名称" />
                </el-form-item>
                <el-form-item label="联系人电话" prop="phone">
                    <el-input v-model="mainCompanyForm.phone" placeholder="请输入联系电话" />
                </el-form-item>
                <!-- 省市区级联 -->
                <el-form-item label="省 / 市 / 区" prop="region">
                    <el-cascader v-model="mainCompanyForm.region" :options="regionData" placeholder="请选择省市区"
                        style="width: 100%" size="small" clearable filterable @change="handleRegionChange" />
                </el-form-item>

                <!-- 详细地址 -->
                <el-form-item label="详细地址" prop="detailAddress">
                    <el-input v-model="mainCompanyForm.detailAddress" placeholder="街道、门牌号、楼栋等" size="small"
                        @input="updateFullAddress" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button type="primary" @click="handleSaveMainCompany" :loading="savingMain">保存</el-button>
                <el-button @click="editMainDialogVisible = false">取消</el-button>
            </template>
        </el-dialog>

        <el-dialog v-model="dialogVisible" title="新增子公司" width="500">
            <el-form :model="form" label-width="80px" :rules="rules" ref="formRef">
                <el-form-item label="上级公司">
                    <el-input :model-value="editingNode?.name" disabled />
                </el-form-item>
                <el-form-item label="公司名称" prop="name">
                    <el-input v-model="form.name" placeholder="请输入公司名称" />
                </el-form-item>
                <el-form-item label="公司编码" prop="code">
                    <el-input v-model="form.code" placeholder="请输入公司编码（唯一）" />
                </el-form-item>


                <el-form-item label="负责人" prop="legalPerson">
                    <el-input prefix-icon="User" v-model="form.legalPerson" />
                </el-form-item>

                <el-form-item label="电话" prop="phone">
                    <el-input prefix-icon="PhoneFilled" v-model="form.phone" />
                </el-form-item>

                <el-form-item label="身份证" prop="idCard">
                    <el-input prefix-icon="Postcard" v-model="form.idCard" />
                </el-form-item>

                <el-form-item label="性别" prop="sex">
                    <el-radio-group v-model="form.sex">
                        <el-radio label="1">男</el-radio>
                        <el-radio label="0">女</el-radio>
                    </el-radio-group>
                </el-form-item>

                <!-- 省市区级联 -->
                <el-form-item label="省 / 市 / 区" prop="region">
                    <el-cascader v-model="form.region" :options="regionData" placeholder="请选择省市区" style="width: 100%"
                        size="small" clearable filterable @change="handleAddRegionChange" />
                </el-form-item>

                <!-- 详细地址 -->
                <el-form-item label="详细地址" prop="detailAddress">
                    <el-input v-model="form.detailAddress" placeholder="街道、门牌号、楼栋等" size="small"
                        @input="updateAddFullAddress" />
                </el-form-item>

            </el-form>
            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleSubmit" :loading="submitting">确定</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { regionData, codeToText } from 'element-china-area-data'
import axios from 'axios'

// 加载状态
const loading = ref(true)
const savingMain = ref(false) // 编辑主公司保存状态
const submitting = ref(false) // 新增/编辑子公司的提交状态

// 当前公司（主公司）信息
const currentCompany = reactive({})

// 所有公司
const companyList = ref([])

// 编辑主公司用的表单，用于暂存修改
const mainCompanyForm = reactive({
    id: null,
    name: '',
    phone: '',
    region: '',
    detailAddress: '',
    address: ''
})
const mainCompanyFormRef = ref()

// 主公司编辑对话框及保存
const editMainDialogVisible = ref(false)
const openEditMainCompany = () => {

    if (currentCompany.address) {
        const parsedData = parseExistingAddress(currentCompany.address)
        // 将当前值复制给编辑表单
        Object.assign(mainCompanyForm, {
            id: currentCompany.id,
            name: currentCompany.name,
            phone: currentCompany.phone,
            region: parsedData.region || [],
            detailAddress: parsedData.detailAddress || '',
        })
    }
    editMainDialogVisible.value = true
}

const checkRegion = (rule, value, callback) => {
    if (!Array.isArray(value) || value.length !== 3) {
        callback(new Error('请选择完整的省 / 市 / 区'))
    } else {
        callback()
    }
}

const checkDetailAddress = (rule, value, callback) => {
    if (!value) {
        callback(new Error('请输入详细地址'))
    } else {
        callback()
    }
}

// 主公司表单校验规则 (新增)
const mainCompanyRules = {
    name: [{ required: true, message: '请输入公司名称', trigger: 'blur' }],
    phone: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
    region: [{ validator: checkRegion, trigger: 'change' }],
    detailAddress: [{ validator: checkDetailAddress, trigger: 'blur' }],
}

// 获取当前公司数据
const getCurrentCompany = async () => {
    try {
        const res = await axios.get('/api/basic/enterprise/getCompanyByCode')

        if (res.data.code === 5200) {
            Object.assign(currentCompany, res.data.company)

        } else {
            ElMessage.error('获取公司数据失败')
        }
    } catch (error) {
        ElMessage.error(error.message)
    }
}

// 获取所有公司
const getAllCompany = async () => {
    loading.value = true
    try {
        const res = await axios.get('/api/basic/enterprise/selectAllCompany')

        if (res.data.code === 5200) {
            companyList.value = res.data.companyList

        } else {
            ElMessage.error('获取公司数据失败')
        }
    } catch (error) {
        ElMessage.error(error.message)
    } finally {
        loading.value = false
    }
}

const treeData = computed(() => {
    const roots = []
    const map = {}
    companyList.value.forEach(item => {
        map[item.id] = { ...item, children: [] }
    })

    companyList.value.forEach(item => {
        if (item.parentId === null || item.parentId === '0') {
            roots.push(map[item.id])
        } else {
            const parentObj = map[item.parentId]
            if (parentObj) {
                parentObj.children.push(map[item.id])
            }
        }
    })
    return roots
})

// 解析现有地址
const parseExistingAddress = (address) => {
    if (!address) return { region: [], detailAddress: '' }

    try {
        const parts = address.split(' ')
        if (parts.length >= 3) {
            const provinceName = parts[0]
            const cityName = parts[1]
            const districtName = parts[2]
            const detailAddress = parts.slice(3).join(' ') || ''

            const regionCodes = findRegionCodes(provinceName, cityName, districtName)
            return { region: regionCodes, detailAddress }
        }
        return { region: [], detailAddress: address }
    } catch (error) {
        return { region: [], detailAddress: address }
    }
}

// 查找地区代码
const findRegionCodes = (provinceName, cityName, districtName) => {
    try {
        for (const province of regionData) {
            if (codeToText[province.value] === provinceName) {
                if (province.children) {
                    for (const city of province.children) {
                        if (codeToText[city.value] === cityName) {
                            if (city.children) {
                                for (const district of city.children) {
                                    if (codeToText[district.value] === districtName) {
                                        return [province.value, city.value, district.value]
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return []
    } catch (error) {
        return []
    }
}



// 通用函数：根据 region 数组和详细地址，生成完整地址字符串
const buildFullAddress = (region, detailAddress) => {
    // 如果 region 不是长度为3的数组，直接返回详细地址（或空）
    if (!Array.isArray(region) || region.length !== 3) {
        return detailAddress?.trim() || ''
    }

    const [provinceCode, cityCode, districtCode] = region

    const province = codeToText[provinceCode] || ''
    const city = codeToText[cityCode] || ''
    const district = codeToText[districtCode] || ''

    // 如果任一级地区解析失败，也只返回详细地址
    if (!province || !city || !district) {
        return detailAddress?.trim() || ''
    }

    const regionText = `${province} ${city} ${district}`
    return detailAddress ? `${regionText} ${detailAddress}`.trim() : regionText
}

const updateFullAddress = () => {
    mainCompanyForm.address = buildFullAddress(mainCompanyForm.region, mainCompanyForm.detailAddress)
}

const handleRegionChange = (value) => {
    mainCompanyForm.region = Array.isArray(value) ? value : []
    updateFullAddress()
}


const updateAddFullAddress = () => {
    form.address = buildFullAddress(form.region, form.detailAddress)
}

const handleAddRegionChange = (value) => {
    form.region = Array.isArray(value) ? value : []
    updateAddFullAddress()
}

//保存主公司信息 - 调用后端接口
const handleSaveMainCompany = async () => {
    await mainCompanyFormRef.value?.validate(async (valid) => {
        if (!valid) return

        savingMain.value = true
        updateFullAddress()
        try {
            const res = await axios.post('/api/basic/enterprise/updateCompany', mainCompanyForm)

            if (res.data.code === 5200) {
                ElMessage.success(res.data.msg)
                // 成功后，更新前端显示数据
                Object.assign(currentCompany, mainCompanyForm)
                editMainDialogVisible.value = false
            } else {
                ElMessage.error(res.data.msg)
            }
        } catch (error) {
            ElMessage.error('网络或服务器错误')
            console.error('保存主公司信息错误:', error)
        } finally {
            savingMain.value = false
        }
    })
}

// 对话框
const dialogVisible = ref(false)
const editingNode = ref(null) // 当前编辑的节点（作为父节点）
const formRef = ref()
const form = reactive({
    name: '',
    code: '',
    legalPerson: '',    // 公司法人
    phone: '',          // 联系电话
    idCard: '',         // 身份证号
    sex: '1',           // 性别，默认男
    region: [],
    detailAddress: '',
    address: '',         // 完整地址：省市区 + 详细地址
})



// 手机号正则
const phonePattern = /^1[3-9]\d{9}$/

// 身份证号简单校验（可按需增强）
const idCardPattern = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/

const checkName = (rule, value, callback) => {
    if (!value) {
        callback(new Error('用户名不能为空'))
    } else {
        callback()
    }
}

const checkCode = (rule, value, callback) => {
    if (!value) {
        callback(new Error('公司编码不能为空'))
    } else {
        callback()
    }
}

const checkLegalPerson = (rule, value, callback) => {
    if (!value) {
        callback(new Error('联系人不能为空'))
    } else {
        callback()
    }
}

const checkPhone = (rule, value, callback) => {
    if (!value) {
        callback(new Error('联系电话不能为空'))
    } else if (!phonePattern.test(value)) {
        callback(new Error('请输入正确的手机号'))
    } else {
        callback()
    }
}

const checkIdCard = (rule, value, callback) => {
    if (!value) {
        callback(new Error('身份证号码不能为空'))
    } else if (!idCardPattern.test(value)) {
        callback(new Error('身份证号码格式不正确'))
    } else {
        callback()
    }
}

const rules = {
    name: [{ validator: checkName, trigger: 'blur' }],
    code: [{ validator: checkCode, trigger: 'blur' }],
    legalPerson: [{ validator: checkLegalPerson, trigger: 'blur' }],
    phone: [{ validator: checkPhone, trigger: 'blur' }],
    idCard: [{ validator: checkIdCard, trigger: 'blur' }],
    region: [{ validator: checkRegion, trigger: 'change' }],
    detailAddress: [{ validator: checkDetailAddress, trigger: 'blur' }],
}

// 打开新增/添加子公司对话框
const openAddDialog = (parentNode) => {
    editingNode.value = parentNode // 设置父节点
    form.name = ''
    form.code = ''
    formRef.value?.resetFields() // 重置表单验证和数据
    dialogVisible.value = true
}

// 新增子公司
const handleSubmit = async () => {
    await formRef.value?.validate(async (valid) => {
        if (!valid) return

        submitting.value = true
        updateAddFullAddress()

        try {
            const payload = {
                parentId: editingNode.value.id, // 父公司 ID
                level: editingNode.value.level + 1, // 父公司 Level 
                name: form.name,
                code: form.code,
                legalPerson: form.legalPerson,
                phone: form.phone,
                idCard: form.idCard,
                sex: form.sex,
                address: form.address // ✅ 关键：提交完整地址
            }

            const res = await axios.post('/api/basic/enterprise/addCompany', payload) // 假设新增子公司接口

            if (res.data.code === 5200) {
                ElMessage.success('子公司添加成功')
                // 成功后，重新获取公司树数据
                getAllCompany()
                dialogVisible.value = false
            } else {
                ElMessage.error(res.data.msg || '添加失败')
            }
        } catch (error) {
            ElMessage.error('网络或服务器错误')
            console.error('新增子公司错误:', error)
        } finally {
            submitting.value = false
        }
    })
}

// 删除子公司
const handleDelete = async (node) => {

    console.log(node.id)

    try {
        await ElMessageBox.confirm(`确定删除公司 “${node.name}” 及其所有子公司？`, '删除子公司', { type: 'warning' })
    } catch {
        return ElMessage.info('取消删除')
    }

    try {
        const res = await axios.post('/api/basic/enterprise/deleteCompany', null, { params: { id: node.id } }) // 假设删除接口

        if (res.data.code === 5200) {
            ElMessage.success('删除成功')
            getAllCompany()
        } else {
            ElMessage.error(res.data.msg || '删除失败')
        }
    } catch (error) {
        ElMessage.error('网络或服务器错误')
        console.error('删除公司错误:', error)
    }
}



// 辅助：显示层级
const getLevelText = (level) => {
    const levels = ['总公司', '一级子公司', '二级子公司', '三级子公司']
    return levels[level] || ''
}

// 在组件挂载时调用获取数据的方法
onMounted(() => {
    getCurrentCompany()
    getAllCompany()
})
</script>

<style scoped>
.company-page {
    padding: 20px;
}

.cell-item {
    display: flex;
    align-items: center;
}
</style>
